<?php

namespace app\common\model\order;

use app\common\model\BaseModel;
use app\common\model\user\User;
use app\common\model\order\Order as OrderModel;

/**
 * 推荐订单管理模型
 */
class OrderReferee extends BaseModel
{
	protected $name = 'order_referee';
	protected $pk = 'order_referee_id';

    /**
     * 追加字段
     * @var array
     */
    protected $append = [
        'first_order',   // 创建时间
    ];

    // 20240611 Mr.Z 修改首单算法
    public function getFirstOrderAttr($value, $data)
    {
        return (new OrderModel())->where("user_id", $data["user_id"])
            ->where("order_source", "<>", 80)
            ->where("pay_status", "=", "20")
            ->where("order_status", "<>", "20")
            ->order("pay_time")
            ->value("order_id") == $data['order_id'];
//        return $this->where(['referee_id' => $data['referee_id']])->count() == 1;
    }

	/**
	 * 关联用户表
	 */
	public function user()
	{
		return $this->belongsTo('app\\common\\model\\user\\User');
	}

	/**
	 * 关联订单主表
	 */
	public function orderMaster()
	{
		return $this->belongsTo('app\\common\\model\\order\\Order');
	}

	/**
	 * @Exp    更新推荐订单
	 * @Author Mr.Z
	 * @Date   2024-02-20
	 * @param  [type]     $orderInfo [description]
	 * @param  [type]     $user_id  [description]
	 */
	public static function RefereeOrderCompleted($orderInfo)
	{
		$model = new static();
        // 20240325 joey 去掉首单写入判断
		/*$Refereeorder = $model->where(['user_id' => $orderInfo['user_id']])->find();
		if($Refereeorder) return;*/
        $referer = User::where(['user_id' => $orderInfo['user_id']])->find();
		return $model->createData([
			'order_id'	=>	$orderInfo['order_id'],
			'total_price'	=>	$orderInfo['total_price'],
			'order_price'	=>	$orderInfo['order_price'],
			'coupon_money_sys'	=>	$orderInfo['coupon_money_sys'],
			'points_money'	=>	$orderInfo['points_money'],
			'points_num'	=>	$orderInfo['points_num'],
			'pay_price'	=>	$orderInfo['pay_price'],
			'receipt_time'	=>	time(),
			'user_id'	=>	$orderInfo['user_id'],
			'referee_id' =>	$referer['referee_id'] ?? 0,
		]);
	}

	public static function createData($where)
	{
		$model = new static();
		$where['app_id'] = self::$app_id;
		$data = $model->save($where);
		return $data;
	}

	
}
